<template>
  <div>
    <!-- 表单查询 -->
    <div class="top inspect-box">
      <Tabs v-model:activeKey="activeKey" @change="onChangeTabs">
        <Tabs.TabPane key="inspect" tab="检查记录"></Tabs.TabPane>
        <Tabs.TabPane key="set" tab="设置" force-render style="width: 100%">
          <div v-if="activeKey === 'set'" class="below">
            <div class="deduct-points">
              <div class="small-title">删除设置</div>
              <div class="set-options">
                <span>打分记录可删除时间：</span>
                <a-select
                  ref="select"
                  v-model:value="setData.deleteDayNum"
                  style="width: 100px"
                  @change="onFinish"
                >
                  <a-select-option :value="7">近7天</a-select-option>
                  <a-select-option :value="30">近30天</a-select-option>
                  <a-select-option :value="180">近180天</a-select-option>
                  <a-select-option :value="365">近一年</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="deduct-points">
              <div class="small-title">重新提交设置</div>
              <div class="set-options">
                <span style="margin-left: 15px">重新提交可用时间：</span>
                <a-select
                  ref="select"
                  v-model:value="setData.resubmitDayNum"
                  style="width: 100px"
                  @change="onFinish"
                >
                  <a-select-option :value="7">近7天</a-select-option>
                  <a-select-option :value="30">近30天</a-select-option>
                  <a-select-option :value="180">近180天</a-select-option>
                  <a-select-option :value="365">近一年</a-select-option>
                </a-select>
              </div>
            </div>
            <div class="set-btn">
              <a-button type="primary" :loading="btnLoading" html-type="submit" @click="submit"
                >保存</a-button
              >
            </div>
          </div>
        </Tabs.TabPane>
      </Tabs>
      <Form
        v-if="activeKey === 'inspect'"
        ref="formRef"
        name="advanced_search"
        class="ant-advanced-search-form"
        :model="formState"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        @finish="onFinish"
      >
        <Row :gutter="[16, 1]">
          <Col :span="6">
            <Form.Item label="宿舍楼">
              <a-select
                ref="select"
                v-model:value="formState.data.dormitoryId"
                placeholder="请选择"
                allow-clear
                :get-popup-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                @change="onSelectDormitory"
              >
                <a-select-option
                  v-for="(item, index) of optionList.dormitoryList"
                  :key="index"
                  :value="item.id"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
            </Form.Item>
          </Col>
          <Col :span="6">
            <Form.Item label="房间名">
              <!-- <a-select ref="select" v-model:value="formState.data.rName" @change="onFinish">
                <a-select-option value="">全部</a-select-option>
              </a-select> -->
              <a-cascader
                v-model:value="formState.data.rName"
                allow-clear
                :options="optionList.roomList"
                placeholder="请选择"
                :load-data="onLoadDataRoom"
                :field-names="{ label: 'name', value: 'id' }"
                :get-popup-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                @change="onChangeRoom"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="检查时间">
              <a-range-picker
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始日期', '结束日期']"
                :value="formState.data.createValue"
                :get-calendar-container="
                  triggerNode => {
                    return triggerNode.parentNode;
                  }
                "
                :allow-clear="true"
                @change="examineTime"
              />
            </Form.Item>
          </Col>
        </Row>
        <div class="search">
          <div class="search-btn">
            <a-button type="primary" html-type="submit" @click="onSearch(1)">查询</a-button>
            <a-button ghost style="margin: 0 0 0 16px" @click="resetForm">重置</a-button>
          </div>
        </div>
      </Form>
    </div>
    <!-- 列表 -->
    <div v-if="activeKey === 'inspect'" class="below">
      <!-- 表格 -->
      <div>
        <a-table
          :columns="columns"
          :data-source="tableData.records"
          :row-key="record => record.id"
          :pagination="false"
          :loading="loading"
          :scroll="{ x: 1300 }"
        >
          <!-- <template v-slot:emptyText>
            <span>{{ loading ? '' : '暂无数据' }}</span>
          </template> -->
          <template v-slot:emptyText>
            <div class="zz-global-nodata">
              <img
                v-if="searchStatus * 1 === 0"
                src="@/assets/images/accommodation/default-no-data.png"
                alt=""
              />
              <img v-else src="@/assets/images/accommodation/no-data-search-new.png" alt="" />
            </div>
          </template>
          <!-- v-if="emptyStatus" -->
          <!-- <template v-slot:emptyText>
            <span>暂无数据</span>
          </template> -->

          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'itemNames'">
              <div
                style="
                  font-size: 14px;
                  color: #222222;
                  width: 170px;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
              >
                <Tooltip
                  :overlay-style="{ whiteSpace: 'normal' }"
                  :get-popup-container="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  :auto-adjust-overflow="true"
                  placement="topLeft"
                  :title="record.itemNames"
                >
                  {{ record.itemNames }}
                </Tooltip>
              </div>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button type="primary" size="small" ghost @click="onDeta(record.id)">查看</a-button>
            </template>
          </template>
        </a-table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <span style="color: #999999; margin-right: 8px">共{{ tableData.pages }}页</span>
        <a-pagination
          v-model:current="tableData.current"
          v-model:pageSize="tableData.size"
          :page-size-options="pageSizeOptions"
          show-quick-jumper
          :total="tableData.total"
          :show-size-changer="true"
          @change="onChangePagination"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Form, Row, Col, Tabs, message, Cascader, Tooltip } from 'ant-design-vue';
import {
  getExamineRecording,
  getExamineSettingResubmit,
  setUpdateMarkModel,
  dormitoryDetails
} from '@/api/assessment/inspect';
import { getDormitory, floorList, floorRoom, roomBedNum } from '@/api/common';
import moment from 'moment';
import dayjs from 'dayjs';
import { debounce } from '@/utils/debounce.js';
const router = useRouter();
const dayCreateValue = ref([
  dayjs(moment().format('YYYY-MM-DD 00:00')),
  dayjs(moment().format('YYYY-MM-DD 23:59'))
]);
// 时间设置
let startTime = moment(new Date(new Date(new Date().toLocaleDateString()).getTime())).format(
  'YYYY-MM-DD HH:mm:ss'
);
let endTime = moment(
  new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
).format('YYYY-MM-DD HH:mm:ss');
const formState = ref({
  data: {
    dormitoryId: null, // 宿舍楼
    rName: [], // 房间名称
    examineStartTime: startTime, // 开始时间
    examineStopTime: endTime, // 结束时间
    createValue: dayCreateValue.value,
    roomId: null
  },
  size: 10, // 条数
  current: 1 // 页码
});
const searchStatus = ref(0);
onMounted(() => {
  let inspectQuery = localStorage.getItem('inspectQuery');

  if (!inspectQuery || inspectQuery === null || inspectQuery === undefined) {
    dayCreateValue.value = [
      dayjs(moment().format('YYYY-MM-DD 00:00')),
      dayjs(moment().format('YYYY-MM-DD 23:59'))
    ];
  }
  // getTabsList(formState.value);
  obtainQuery();
});
function obtainQuery() {
  let inspectQuery = localStorage.getItem('inspectQuery');
  console.log('我cnim检查记录', inspectQuery);
  if (inspectQuery && inspectQuery !== null) {
    let inspectQueryJson = JSON.parse(inspectQuery);
    optionList.value = inspectQueryJson.optionList;
    activeKey.value = inspectQueryJson.activeKey;
    formState.value = inspectQueryJson.formState;
    console.log('ppp', inspectQueryJson);

    if (!inspectQuery || inspectQuery === null || inspectQuery === undefined) {
      dayCreateValue.value = [
        dayjs(moment().format('YYYY-MM-DD 00:00')),
        dayjs(moment().format('YYYY-MM-DD 23:59'))
      ];
      formState.value.data.createValue = dayCreateValue.value;
    } else {
      if (formState.value.data.examineStartTime && formState.value.data.examineStartTime !== null) {
        dayCreateValue.value = [
          dayjs(moment().format(formState.value.data.examineStartTime)),
          dayjs(moment().format(formState.value.data.examineStopTime))
        ];
      } else {
        dayCreateValue.value = [];
      }
      formState.value.data.createValue = dayCreateValue.value;
      console.log('wcndlgd', formState.value.data.createValue);
      if (formState.value.data.rName.length > 0) {
        formState.value.data.roomId =
          formState.value.data.rName[formState.value.data.rName.length - 1];
      }
      // if (formState.value.data.rName.length === 2) {
      //   formState.value.data.roomId = formState.value.data.rName[1];
      // }
    }
    console.log('ojbk----', formState.value);
    console.log('inspectQueryJson', inspectQueryJson);
    console.log('activeKey.value', activeKey.value);
    getTabsList(formState.value);
  } else {
    getRoomBedNum();
    getDormitoryList();
    getTabsList(formState.value);
  }
}
const loading = ref(true);
// 表格信息
const tableData = ref([]);
const emptyStatus = ref(false);
// 下拉选项列表
const optionList = ref({
  dormitoryList: [],
  roomList: [],
  roomBedNum: []
});
// 获取宿舍楼列表
const getRoomBedNum = () => {
  roomBedNum().then(res => {
    if (res.data.code === 200) {
      optionList.value.roomBedNum = res.data.data;
    }
  });
};
// 获取宿舍楼列表
const getDormitoryList = () => {
  getDormitory(0).then(res => {
    if (res.data.code === 200) {
      optionList.value.dormitoryList = res.data.data;
      optionList.value.roomList = res.data.data;
      optionList.value.roomList.forEach(elem => {
        elem.isLeaf = false;
      });
    }
  });
};
// 获取宿舍楼层列表
const getFloorList = value => {
  floorList(value).then(res => {
    if (res.data.code === 200) {
      res.data.data.forEach(elem => {
        let obj = {
          name: `${elem.storey}楼`,
          storey: elem.storey,
          id: elem.storey,
          dormitoryId: elem.id,
          floor: elem.floor,
          isLeaf: false
        };
        optionList.value.roomList.push(obj);
      });
    }
  });
};
// 改变宿舍楼回调
const onSelectDormitory = value => {
  formState.value.data.rName = [];
  optionList.value.roomList = [];
  if (value !== undefined) {
    getFloorList(value);
  } else {
    getDormitoryList();
  }
};
// 选择房间回调
const onChangeRoom = (value, selectedOptions) => {
  // if (selectedOptions.length > 0) {
  console.log('房间', value, selectedOptions[0]);
  // if (selectedOptions[0].dormitoryId !== undefined) {
  //   formState.value.data.dormitoryId = selectedOptions[0].dormitoryId;
  // } else {
  //   formState.value.data.dormitoryId = value[0];
  // }
  // }
  if (value.length === 3) {
    formState.value.data.dormitoryId = value[0];
  }
};
// 选择房间异步动态加载
const onLoadDataRoom = selectedOptions => {
  if (!formState.value.data.dormitoryId) {
    formState.value.data.dormitoryId = selectedOptions[0].id;
  }

  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true; // load options lazily
  if (targetOption.dormitoryName) {
    floorList(targetOption.id).then(res => {
      if (res.data.code === 200) {
        targetOption.loading = false;
        targetOption.children = [];
        res.data.data.forEach(elem => {
          let obj = {
            name: `${elem.storey}楼`,
            id: elem.storey,
            storey: elem.storey,
            floor: elem.floor,
            isLeaf: false
          };
          targetOption.children.push(obj);
        });
        optionList.value.roomList = [...optionList.value.roomList];
      }
    });
  }
  if (targetOption.floor) {
    let id = selectedOptions[0].floor ? formState.value.data.dormitoryId : selectedOptions[0].id;
    floorRoom(id, targetOption.storey).then(res => {
      if (res.data.code === 200) {
        targetOption.loading = false;
        targetOption.children = [];
        res.data.data.forEach(elem => {
          let obj = {
            name: elem.name,
            id: elem.id,
            isLeaf: true
          };
          targetOption.children.push(obj);
        });
        optionList.value.roomList = [...optionList.value.roomList];
      }
    });
  }
};
// 获取表格信息
function getTabsList(data) {
  console.log(data, '+++++++++++++++++');
  getExamineRecording(data).then(res => {
    if (res.data.code === 200) {
      tableData.value = res.data.data;
      loading.value = false;
      setTimeout(() => {
        emptyStatus.value = true;
      }, 300);
    }
  });
}

// 重置
const resetForm = () => {
  searchStatus.value = 0;
  formState.value.data.createValue = dayCreateValue.value;
  formState.value.data.dormitoryId = null;
  formState.value.data.rName = [];
  formState.value.data.roomId = null;
  formState.value.data.examineStartTime = startTime;
  formState.value.data.examineStopTime = endTime;
  dayCreateValue.value = [
    dayjs(moment().format('YYYY-MM-DD 00:00')),
    dayjs(moment().format('YYYY-MM-DD 23:59'))
  ];
  formState.value.size = 10;
  formState.value.data.createValue = dayCreateValue.value;
  // formRef.value.resetFields();
  onSearch();
  getDormitoryList();
};

// 查询 按钮
const onSearch = status => {
  // 手动点击
  if (status * 1 === 1) {
    searchStatus.value = 1;
    formState.value.current = 1;
  }
  formState.value.data.roomId = formState.value.data.rName.length
    ? formState.value.data.rName[formState.value.data.rName.length - 1]
    : null; // 宿舍楼房间

  getTabsList(formState.value);
};

const setData = ref({
  id: '',
  deleteDayNum: null,
  resubmitDayNum: null
});

// tabs改变回调
const onChangeTabs = value => {
  searchStatus.value = 0;
  // let inspectQuery = localStorage.getItem('inspectQuery');
  // console.log('切换', value);
  // localStorage.removeItem('inspectQuery');
  emptyStatus.value = false;
  if (value === 'set') {
    getExamineSettingResubmit().then(res => {
      if (res.data.code === 200) {
        setData.value = res.data.data;
      }
    });
  }
  if (value === 'inspect') {
    let obj = {
      data: formState.value.data,
      current: tableData.value.current,
      size: tableData.value.size
    };
    getTabsList(obj);
  }
  resetForm();
};
// tabs 激活标签
const activeKey = ref('inspect');
// 页码
const current = ref(1);
// 指定每页条数
const pageSizeOptions = ref(['10', '20', '30', '40', '50', '100', '500', '1000']);
// 分页发生改变
const onChangePagination = value => {
  formState.value.data.roomId = formState.value.data.rName.length
    ? formState.value.data.rName[formState.value.data.rName.length - 1]
    : null; // 宿舍楼房间
  let obj = {
    data: formState.value.data,
    current: tableData.value.current,
    size: tableData.value.size
  };
  formState.value.current = tableData.value.current;
  formState.value.size = tableData.value.size;
  getTabsList(obj);
};
// 查看详情
const onDeta = id => {
  saveQuery();
  console.log('点了查看按钮');
  let obj = {
    examineId: id
  };
  dormitoryDetails(obj).then(res => {
    console.log('点了查看按钮的结果是什么', res);
    if (res.data.code === 200) {
      router.push({
        path: '/inspect/details',
        query: {
          examineId: id
        }
      });
    } else {
      message.error(res.data.msg);
      onSearch();
    }
  });
  // router.push({
  //   path: '/inspect/details',
  //   query: {
  //     examineId: id
  //   }
  // });
};
function saveQuery() {
  let json = {
    activeKey: activeKey.value,
    formState: formState.value,
    optionList: optionList.value
  };
  console.log('保存的时候检查记录', json);
  localStorage.setItem('inspectQuery', JSON.stringify(json));
}
const btnLoading = ref(false);
const submit = debounce(function () {
  btnLoading.value = true;
  setUpdateMarkModel(setData.value)
    .then(res => {
      if (res.data.code === 200) {
        message.success(res.data.msg);
      }
      btnLoading.value = false;
    })
    .catch(() => {
      btnLoading.value = false;
    });
}, 500);

console.log(dayCreateValue.value, 'dayCreateValue.value');
console.log(formState.value.data.createValue, '888');
const columns = reactive([
  {
    key: 'roomName',
    title: '房间名称',
    dataIndex: 'roomName',
    scopedSlots: { customRender: 'roomName' },
    fixed: 'left'
  },
  {
    key: 'dormitoryName',
    title: '宿舍楼',
    dataIndex: 'dormitoryName',
    scopedSlots: { customRender: 'dormitoryName' }
  },
  {
    key: 'examineGrade',
    title: '评分等级',
    dataIndex: 'examineGrade',
    scopedSlots: { customRender: 'examineGrade' }
  },
  {
    key: 'totalMarkScore',
    title: '得/扣分',
    dataIndex: 'totalMarkScore',
    scopedSlots: { customRender: 'totalMarkScore' }
  },
  {
    key: 'itemNames',
    title: '扣分项',
    dataIndex: 'itemNames',
    scopedSlots: { customRender: 'itemNames' }
  },
  {
    key: 'examineTime',
    title: '检查时间',
    dataIndex: 'examineTime',
    scopedSlots: { customRender: 'examineTime' }
  },
  {
    title: '操作',
    key: 'action',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    fixed: 'right',
    width: 100
  }
]);

// 表单查询
const formRef = ref();
// label样式
// const labelCol = reactive({
//   xs: { span: 4 },
//   sm: { span: 6 }
// });
// const wrapperCol = reactive({
//   xs: { span: 24 },
//   sm: { span: 16 }
// });
const labelCol = reactive({
  xs: { span: 8 },
  xl: { span: 8 },
  xxl: { span: 6 }
});
const wrapperCol = reactive({
  xs: { span: 24 },
  xl: { span: 24 },
  xxl: { span: 24 }
});
const onFinish = values => {
  console.log('formState: ', formState);
  let parmas = {
    name: formState.value.name,
    grade: formState.value.grade,
    infoClass: formState.value.infoClass,
    dormitory: formState.value.dormitory,
    sex: formState.value.sex,
    className: formState.value.className,
    studentState: formState.value.studentState,
    allocationStatus: formState.value.allocationStatus,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  };
  console.log(parmas);
};
// 日期转换
function rTime(date) {
  let json_date = new Date(date).toJSON();
  return new Date(new Date(json_date) + 8 * 3600 * 1000)
    .toISOString()
    .replace(/T/g, ' ')
    .replace(/\.[\d]{3}Z/, '');
}
/* function onRangeOk(dateString) {
  formState.value.data.examineStartTime = rTime(dateString[0]);
  formState.value.data.examineStopTime = rTime(dateString[1]);
} */
function examineTime(dates, dateString) {
  formState.value.data.createValue = dates;
  formState.value.data.examineStartTime = dateString[0];
  formState.value.data.examineStopTime = dateString[1];
}
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(500);
</script>

<style lang="less" scoped>
.top,
.below {
  width: 100%;
  padding: 24px 0;
  background: #ffffff;
  border-radius: 4px;
  // min-width: 1000px;
}
.below {
  padding: 24px;
  min-height: 710px;

  .ranking {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #e1dddd;
    padding-bottom: 16px;
    margin-bottom: 16px;
    &-text {
      font-size: 18px;
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      font-weight: 500;
      color: #222222;
    }
  }
  .search {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 24px;
    .search-btn-left {
      width: 40%;
      display: flex;
      justify-content: flex-start;
      a-button {
        margin-left: 16px;
      }
    }
    .search-btn-right {
      width: 40%;
      display: flex;
      justify-content: flex-end;
    }
  }
  /deep/.micro-dormitory-empty-normal .micro-dormitory-empty-image {
    height: 100px;
  }
  /deep/.micro-dormitory-empty-img-simple {
    width: 100px;
    height: 80px;
  }
  .deduct-points {
    margin-bottom: 32px;
    .small-title {
      font-size: 18px;
      font-family: Source Han Sans CN, Source Han Sans CN-Medium;
      font-weight: 500;
      color: #222222;
    }
    .set-options {
      font-size: 14px;
      color: #666666;
      margin-top: 20px;
    }
  }
  .set-btn {
    display: flex;
    justify-content: flex-end;
    width: 100%;
  }
}
.top {
  margin-bottom: 24px;
  .search {
    display: flex;
    justify-content: flex-end;
    margin-right: 22px;
  }
}
.pagination {
  align-items: center;
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}
/deep/.micro-dormitory-tabs-tab {
  font-size: 16px;
  padding: 12px 24px;
}
/deep/.micro-dormitory-select-arrow {
  top: 40%;
}
/deep/.micro-dormitory-select-selection-item {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  width: 8rem !important;
}
// /deep/.micro-dormitory-cascader-menu {
//   white-space: nowrap !important;
//   overflow: hidden !important;
//   text-overflow: ellipsis !important;
//   width: 270px !important;
// }
/deep/.micro-dormitory-cascader-menu-item-content,
/deep/.micro-dormitory-cascader-menu-item,
/deep/.micro-dormitory-cascader-menu-item-expand {
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  width: 270px !important;
}
/deep/.micro-dormitory-table-content {
  min-height: 63vh;
}
.inspect-box /deep/.micro-dormitory-tabs-nav-wrap {
  // border: 1px solid #f00;
  padding-left: 50px;
}

:deep(.micro-dormitory-form-item-label) {
  max-width: 90px;
}
</style>
